package com.bac.rentmap.ad.flat.user.review;

import java.util.HashSet;
import java.util.Set;

import javax.jdo.PersistenceManager;

import org.springframework.beans.factory.annotation.Required;

import com.bac.rentmap.ad.flat.FlatAd;
import com.bac.rentmap.ad.flat.jdo.CachingJdoFlatAdDao;
import com.bac.rentmap.ad.flat.rating.item.UserReviewRatingItemCalculator;
import com.bac.rentmap.jdo.JdoSupport;

public abstract class AbstractReviewCountIncrementer extends JdoSupport
        implements ReviewCountIncrementer {
    private CachingJdoFlatAdDao flatAdDao;

    public FlatAd inc(Long flatAdId, String reviewer) {
        PersistenceManager persistenceManager = getPersistenceManager();
        try {
            FlatAd res = persistenceManager.getObjectById(FlatAd.class,
                    flatAdId);
            if (res != null) {
                Integer count = getUserReviewCount(res);
                if (count == null) {
                    count = 0;
                }
                setUserReviewCount(res, ++count);
                if(count < UserReviewRatingItemCalculator.MAX_VALUABLE_USER_REVIEW_COUNT){
                    res.setRatingCalculated(false);
                }
                Set<String> reviewers = res.getReviewers();
                if(reviewers == null){
                    res.setReviewers(reviewers = new HashSet<String>());
                }
                if(reviewers.add(reviewer))
                  flatAdDao.removeFromCache(flatAdId);
            }
            return res;

        } finally {
            persistenceManager.close();
        }
    }

    protected abstract Integer getUserReviewCount(FlatAd flatAd);

    protected abstract void setUserReviewCount(FlatAd flatAd, Integer count);

    @Required
    public void setFlatAdDao(CachingJdoFlatAdDao flatAdDao) {
      this.flatAdDao = flatAdDao;
    }
}
